import os

import toml
from PyQt5.QtWidgets import QMessageBox

TOML_PATH = "config.toml"

local_dic = {}

init_conf = {
    "title": "config",
    "number": 0,
    "login_url": "http://220.163.44.146:9001/cwbase/web/login.aspx",
    "main_name": "main.aspx",
    "username": "ygmg006115",
    "password": "lw081105#",
    "query_wait": 0.6
}


def write(dic: dict):
    try:
        local_dic.update(dic)
        with open(TOML_PATH, "w", encoding="utf-8") as fs:
            toml.dump(local_dic, fs)
        fs.close()
        return True
    except Exception as e:
        print(e)
        return False


def read():
    global local_dic
    try:
        with open(TOML_PATH, "r+", encoding="utf-8") as fs:
            # 判断是否包含初始化的keys
            d = toml.load(fs)
            for key in init_conf.keys():
                if key not in d.keys():
                    d[key] = init_conf.get(key)
            fs.seek(0)
            toml.dump(d, fs)
            local_dic = d
        fs.close()
        return get()
    except Exception as e:
        print(e)
        QMessageBox.critical(None, "错误", "配置文件读取失败,请以管理员身份运行修复工具")
        print(str(e))
        return False


# 程序启动必须调用一次
def init():
    global local_dic
    if not os.path.exists(TOML_PATH):  # 如果文件不存在
        write(init_conf)
    return read()


def update(key, value):
    dic = get()
    dic[key] = value
    return write(dic)


def get(key=None):
    if key is None:
        return local_dic
    else:
        return local_dic.get(key)
